<?php

/**
 * 历史宣教
 */

namespace app\common\model;

use app\common\lib\ZhyxMongo;
use think\facade\Cache;
use app\common\model\PatientInfo as PatientInfoModel;
use app\common\model\search\PropagandaEducationHistorySearch;
use app\common\model\PropagandaEducation as PropagandaEducationModel;
use catchAdmin\permissions\model\Users as UsersModel;
use app\common\model\PushMessage as PushMessageModel;
use think\Paginator;
use think\Collection;

class PropagandaEducationHistory extends BaseModel
{
    use PropagandaEducationHistorySearch;

    protected $name = "propaganda_education_history";

    /**
     * 获取数据列表
     * @param array $param
     * @return array
     */
    public function getList(array $param=[]): array
	{
        $users = $this->getUserIds();

        $match["deleted_at"] = 0;
        if (!empty($users)) {
            $match['creator_id'] = ['$in' => $users];
        }

        if (isset($param['batch_name']) && !empty($param['batch_name'])) {
            $match['batch_name'] = ['$regex' => $param['batch_name']];
        }

        //batch_no字段必须存在
        $match['batch_no'] = ['$exists' => true];

        $countPip = [['$match' => $match ?: (object)[]],['$group' => ['_id' => '$batch_no']], ['$count' => 'total_count']];
        //计算总条数
        $countResult = ZhyxMongo::getInstance()->setCollection($this->name)->aggregate($countPip);
        $totalCount = 0;
        foreach ($countResult as $k => $v) {
            $totalCount = $v["total_count"];
        }

        $pip = [['$match' => $match ?: (object)[]],['$group' => ['_id' => ['batch_no' => '$batch_no'], 'batch_name' => ['$first' => '$batch_name'], 'pushtime' => ['$first' => '$pushtime'], 'push_num' => ['$sum' => 1], 'creator_name' => ['$first' => '$creator_name'], 'department_name' => ['$first' => '$department_name'], 'push_people_num' => ['$addToSet' => ['patientId' => '$patientId']], 'read_num' => ['$sum' => ['$cond' => ['if' => ['$and' => [['$eq' => ['$isview', 1]]]], 'then' => 1, 'else' => 0]]]]], ['$project' => ['_id' => '$_id.batch_no', 'push_people_num' => ['$size' => '$push_people_num'], 'batch_name' => '$batch_name', 'pushtime' => '$pushtime', 'push_num' => '$push_num', 'read_num' => '$read_num', 'creator_name' => '$creator_name', 'department_name' => '$department_name']], ['$sort' => ['_id' => -1]],['$skip' => (($this->page - 1) * $this->pageLimit)], ['$limit' => $this->pageLimit]];

        $rets = ZhyxMongo::getInstance()->setCollection($this->name)->aggregate($pip);

        $arr = [];
        foreach ($rets as $k => $v) {
            $arr[] = $v;
        }

        return [
            "count" => $totalCount ?: 0,
            "current" => $this->page,
            "data" => $arr,
            "limit" => $this->pageLimit
        ];
	}

    /**
     * 添加数据
     * @param array $param
     * @return string
     */
    public function addData(array $param): string
    {
        return $this->save($param);
    }

    /**
     * 更新数据
     * @param array $data
     * @return bool
     */
    public function saveData($id, array $data): bool
    {
        $model = self::find($id);
        return $model->save($data);
    }

    /**
     * 获取患者详情宣教中心
     */
    public function getPatientEd($pid)
    {
        return $this->where('pid', $pid)
                ->field('id,creator_name,ed_id,ed_name,pushtime,mode,isview')
                ->order('pushtime', 'desc')
                ->select()
                ->toArray();
    }

    /**
     * 获取我的宣教
     * @param string $patientId 患者id
     * @return Collection
     */
    public function getMyEd(string $patientId): Collection
    {
        return $this->mongoSearch()
                    ->where('patientId', $patientId)
                    ->field('type,ed_id,pushtime,ed_name,isview')
                    ->order('pushtime', 'desc')
                    ->select()
                    ->each(function($item, $key){
                        $hits = Cache::store('redis')->get('my_ed:'.(string)$item['id']);
                        $cover = PropagandaEducationModel::where('id', $item['ed_id'])->field('cover,content')->find();//isview
                        $item['hits']    = $hits?(int)$hits:0;
                        $item['cover']   = isset($cover['cover'])?$cover['cover']:'';
                        $item['content'] = isset($cover['content'])?$cover['content']:'';
                        return $item;
                    });
    }

    /**
     * 医生端发送在院宣教
     * @param array $param
     */
    public function pushYsdData(array $param)
    {
        $user = (new UsersModel)->where('doctor_code', $param['doctor_code'])->field('id,username')->find();

        $datas = [];

        $patientList = (new PatientInfoModel)->whereIn('id', $param['pid'])->field('id,patientId,name')->find()->toArray();

        foreach ($patientList as $key => $val)
        {
            //在院宣教
            $data['type']         = 1;
            $data['pid']          = $val['id'];
            $data['name']         = $val['name'];
            $data['patientId']    = $val['patientId'];
            $data['class_id']     = $param['class_id'];
            $data['class_name']   = $param['class_name'];
            $data['ed_id']        = $param['ed_id'];
            $data['ed_name']      = $param['ed_name'];
            $data['creator_id']   = $user['id'];
            $data['creator_name'] = $user['username'];
            $data['pushtime']     = $param['pushtime'];
            $data['mode']         = $param['mode'];
            $data['isview']       = 0;
            $data['deleted_at']   = 0;
            $datas[] = $data;

            $pushData['type']       = 2;//消息类型 1随访，2宣教
            $pushData['mode']       = $param['mode'];
            $pushData['ed_id']      = $param['ed_id'];
            $pushData['ed_name']    = $param['ed_name'];
            $pushData['class_id']   = $param['class_id'];
            $pushData['class_name'] = $param['class_name'];
            $pushData['creator_id'] = $param['creator_id'];
            $pushData['deleted_at'] = 0;
            $pushData['patientId']  = $val['patientId'];
            $pushData['content']    = '您好'.$val['name'].',为您推送'.$param['ed_name'].'宣教内容';
            $pushDatas[] = $pushData;
        }
        (new PushMessageModel)->saveAll($pushDatas);
        return $this->saveAll($datas);
    }

    /**
     * 医生获取所属在院宣教
     */
    public function getCreatorEd($creator_id)
    {
        $edhs = $this->where('creator_id', $creator_id)
            ->field('ed_id')
            ->select()
            ->toArray();

        $ed_ids = [];
        foreach ($edhs as $key => $val)
        {
            $ed_ids[] = $val['ed_id'];
        }
        $data['total'] = $this->where('creator_id', $creator_id)->count(); 
        $data['yesed'] = (new PropagandaEducationModel)->where('isview', 1)->whereIn('id', $ed_ids)->count();    
        $data['noed']  = (new PropagandaEducationModel)->where('isview', '<>', 1)->whereIn('id', $ed_ids)->count();    
        $data['today'] = $this->where('pushtime', date("Y-m-d"))->count();

        return $data;
    }

    /**
     * 获取一条数据
     */
    public function getOneData(array $where=[], $field = "*")
    {
        return  $this->where($where)->field($field)->find();
    }

    /**
     * 获取宣教记录详情
     * @param array $condition 条件
     * @return array
     */
    public function getEdhistoryDetails(array $condition=[]): array
    {
        $paramArr = ["ed_name" => "ed_name", "creator_name" => "creator_name", "name" => "name", "pushtime" => "pushtime_ymd", "status" => "status", "isview" => "isview"];

        $match = [];
        foreach($paramArr as $k => $v){
            if(isset($condition[$k]) && $condition[$k]!==""){
                switch ($k)
                {
                    case 'creator_name':
                    case 'name':
                    case 'ed_name':
                        $match[$v] = ['$regex'=>$condition[$k]];
                        break;
                    case 'status':
                    case 'isview':
                        $match[$v] = (int)$condition[$k];
                        break;
                    case 'pushtime':
                        $match[$v] = $condition[$k];
                        break;
                    default:
                }
            }
        }

        $match["deleted_at"] = 0;
        $match["batch_no"] = $condition["id"];

        //计算总条数
        $countPip = [['$match' => $match ?: (object)[]],['$group' => ['_id' => '$patientId']], ['$count' => 'total_count']];
        $countResult = ZhyxMongo::getInstance()->setCollection($this->name)->aggregate($countPip);
        $totalCount = 0;
        foreach ($countResult as $k => $v) {
            $totalCount = $v["total_count"];
        }
        $pip = [['$match' => $match],['$group' => ['_id' => '$patientId', 'name' => ['$first' => '$name'], 'sortId' => ['$last' => '$_id'], 'pid' => ['$first' => '$pid'], 'patientId' => ['$first' => '$patientId'], 'detail' => ['$addToSet' => ['pid' => '$pid','patientId' => '$patientId', 'class_name' => '$class_name', 'ed_name' => '$ed_name', 'creator_name' => '$creator_name', 'pushtime' => '$pushtime', 'status' => '$status', 'isview' => '$isview']]]], ['$sort' => ['sortId' => -1]], ['$skip' => (($this->page - 1) * $this->pageLimit)], ['$limit' => $this->pageLimit]];
        $rets = ZhyxMongo::getInstance()->setCollection($this->name)->aggregate($pip);
//        $arr = [];
//        foreach ($rets as $key => $val) {
//            $arr[] = $val;
//        }
//        print_r($rr);exit();
        $arr = [];
        $i = 1;
        foreach ($rets as $k => $v) {
            $val = (array)$v;
            $val['id'] = $i++;

            foreach ($val['detail'] as $k1 => $v1)
            {
                $val['detail'][$k1]['id'] = $i++;
            }
            $arr[] = $val;
        }

        return [
            "count" => $totalCount ?: 0,
            "current" => $this->page,
            "data" => $arr,
            "limit" => $this->pageLimit
        ];
    }

    /**
     * 删除数据
     * @param array $id
     * @return bool
     */
    public function delData(array $id=[]): bool
    {
        return  self::destroy($id);
    }

    /**
     * mongodb聚合查询
     * @param array $pip 条件
     * @return array
     */
    public function mongoAggregate(array $pip=[]): array
    {
        $data = ZhyxMongo::getInstance()->setCollection($this->name)->aggregate($pip);
        $ret = [];
        foreach ($data as $k => $v) {
            $ret[] = $v;
        }
        return $ret;
    }
}